﻿using System.Web;

using Job.Core;
using Job.Core.Web;

namespace Job.ManageMember
{
    /// <summary>
    /// 帐户成员管理。
    /// </summary>
    public static class MemberShip
    {
        #region properties

        private const string cookieName = "inventorysys";
        private const string key = "#colninSysliu%";

        #endregion

        #region methods

        /// <summary>
        /// 用户登出。
        /// </summary>
        public static void LoginOut()
        {
            Cookie.Clear();
        }

        /// <summary>
        /// 用户登录。
        /// </summary>       
        public static User Login(string userName, string userPwd, int expires, CookieExpiresType expiresType, out LoginStatus status)
        {
            User user = User.Login(userName, userPwd, HttpContext.Current.Request.UserHostAddress, out status);

            if (status == LoginStatus.Success && user != null)
            {
                //登录成功。

                Cookie.Set(cookieName, user.KeyId.ToString(), expires, expiresType, key, string.Empty);
                //CookieHelper.SetCookie(cookieName, user.KeyId.ToString(), 10);
            }

            return user;
        }

        #endregion

        #region properties

        /// <summary>
        /// 当前用户。
        /// </summary>
        public static User CurrentUser
        {
            get
            {
                User user = HttpContext.Current.User as User;

                if (user == null)
                {
                    int userId = 0;
                    try
                    {
                        string val = Cookie.Get(cookieName, string.Empty, key);
                        if (!string.IsNullOrEmpty(val)) int.TryParse(val, out userId);
                    }
                    catch
                    {
                        Cookie.Remove(cookieName);                        
                    }

                    user = userId == 0 ? new User() : User.Load(userId);                    
                    HttpContext.Current.User = user;                    
                }

                return user;
            }
        }

        #endregion
    }
}